import {
	defineConfig
} from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import define from './utils/define.js'
console.log(define)
const fs = require('fs');
const manifestPath = `${__dirname}/manifest.json`;
let Manifest = fs.readFileSync(manifestPath, {
	encoding: 'utf-8'
});

function replaceManifest(path, value) {
	const arr = path.split('.');
	const len = arr.length;
	const lastItem = arr[len - 1];
	let i = 0;
	let ManifestArr = Manifest.split(/\n/);

	for (let index = 0; index < ManifestArr.length; index++) {
		const item = ManifestArr[index];
		if (new RegExp(`"${arr[i]}"`).test(item)) ++i;
		if (i === len) {
			const hasComma = /,/.test(item);
			ManifestArr[index] = item.replace(
				new RegExp(`"${lastItem}"[\\s\\S]*:[\\s\\S]*`),
				`"${lastItem}": ${typeof value === 'string'? '"'+value+'"' : value}${hasComma ? ',' : ''}`
			);
			break;
		}
	}
	Manifest = ManifestArr.join('\n');
}
const appid = define.wxAppid;
const name=define.identification=='user'?'灵工用户端':define.identification=='units'?'灵工企业端':'灵工经纪人端'
replaceManifest('mp-weixin.appid', appid);
replaceManifest('name', name);
fs.writeFileSync(manifestPath, Manifest, {
	flag: 'w'
});
export default defineConfig({
	plugins: [
		uni()
	],
	define: {
		"process.env.config": define,
		"process.env": process.env
	},
	server: {
		port: 3800,
		proxy: {
			'/dev': {
				// target: 'http://118.24.147.238:11101', // 目标服务
				target:"https://jjp.cnthr.com",
				changeOrigin: true,
				rewrite: path => path.replace(/^\/dev/, ''),
			},
			'/wss': {
				target: 'wss://jjp.cnthr.com/jjp.cnthr.com/imServer/im', 
				ws: true, 
				changeOrigin: true,
			}
		}
	}
})